package com.zh.coriander.bgctrl;

import com.zh.auction.util.QiniuUtils;
import com.zh.auction.util.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author songjingen
 * @description
 * @date 2020/1/6
 */
@RestController
@RequestMapping("editor")
@Slf4j
public class EditorUploadCtrl {

    @Autowired
    private QiniuUtils qiniuUtils;

    @Value("${qiniu.remoteAddress}")
    private String remoteAddress;

    @PostMapping("ckUploadFiles")
    public JSONObject uploadfile2(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile upfile = multipartRequest.getFile("upload");
        String scope = "public";
        String originalFilename = upfile.getOriginalFilename();
        log.info("上传文件length {}", upfile);
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();

        if (upfile != null) {
            try {
                byte[] fileByte = upfile.getBytes();
                String key = UUIDUtils.random()+"666_"+originalFilename;
                // private：上传到私有域（资格认证处）；public：上传到公有域。
                if ("public".equals(scope)) {
                    //如果是客户版会直接更新用户头像
                    qiniuUtils.uploadFile(fileByte, key);
                    String headUrl = remoteAddress + key;
                    resultMap.put("uploaded", true + "");
                    resultMap.put("url", headUrl);
                } else if ("private".equals(scope)) {
                    qiniuUtils.uploadFile(fileByte, key);
                    resultMap.put("uploaded", true + "");
                    resultMap.put("url", key);
                }
                log.info("文件路径" + key);
                //需要更新缓存
                return JSONObject.fromObject(resultMap);
            } catch (Exception e) {
                log.info("exception " + e);
                resultMap.put("uploaded", false + "");
                map.put("message","could not upload this file");
                resultMap.put("error",map);
                return JSONObject.fromObject(resultMap);
            }
        }
        resultMap.put("uploaded", false + "");
        map.put("message","could not upload this file");
        resultMap.put("error",map);
        return JSONObject.fromObject(resultMap);
    }

    @PostMapping("kindUploadFiles")
    public void kindUploadFiles(HttpServletRequest request, HttpServletResponse response) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile upfile = multipartRequest.getFile("imgFile");
        response.setHeader("Access-Control-Allow-Origin", "*");
        String scope = "public";
        String originalFilename = upfile.getOriginalFilename();
        log.info("上传文件length {}", upfile);
        Map<String, Object> resultMap = new HashMap<>();
        if (upfile != null) {
            try {
                byte[] fileByte = upfile.getBytes();
                String key = UUIDUtils.random()+"666_"+originalFilename;
                // private：上传到私有域（资格认证处）；public：上传到公有域。
                if ("public".equals(scope)) {
                    //如果是客户版会直接更新用户头像
                    qiniuUtils.uploadFile(fileByte, key);
                    String headUrl = remoteAddress + key;
                    resultMap.put("error", 0);
                    resultMap.put("url", headUrl);
                } else if ("private".equals(scope)) {
                    qiniuUtils.uploadFile(fileByte, key);
                    resultMap.put("error", 0);
                    resultMap.put("url", key);
                }
                log.info("文件路径" + key);
                //需要更新缓存
                response.getWriter().write(resultMap.toString());
            } catch (Exception e) {
                log.info("exception " + e);
                resultMap.put("error", 1);
                resultMap.put("message", "上传失败");
                response.getWriter().write(resultMap.toString());
                System.out.println();
            }
        }
        resultMap.put("error", 1);
        resultMap.put("message", "上传失败");
        response.getWriter().write(resultMap.toString());
    }

    @PostMapping("froalaUploadFiles")
    public JSONObject froalaUploadFiles(HttpServletRequest request, HttpServletResponse response) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile upfile = multipartRequest.getFile("file");
        String scope = "public";
        String originalFilename = upfile.getOriginalFilename();
        log.info("上传文件length {}", upfile);
        Map<String, Object> resultMap = new HashMap<>();
        if (upfile != null) {
            try {
                byte[] fileByte = upfile.getBytes();
                String key = UUIDUtils.random()+"666_"+originalFilename;
                // private：上传到私有域（资格认证处）；public：上传到公有域。
                if ("public".equals(scope)) {
                    //如果是客户版会直接更新用户头像
                    qiniuUtils.uploadFile(fileByte, key);
                    String headUrl = remoteAddress + key;
                    resultMap.put("link", headUrl);
                } else if ("private".equals(scope)) {
                    qiniuUtils.uploadFile(fileByte, key);
                    resultMap.put("link", key);
                }
                log.info("文件路径" + key);
                //需要更新缓存
                return JSONObject.fromObject(resultMap);
            } catch (Exception e) {
                log.info("exception " + e);
                resultMap.put("link", "上传失败");
                return JSONObject.fromObject(resultMap);
            }
        }
        resultMap.put("link", "上传失败");
        return JSONObject.fromObject(resultMap);
    }
}
